package co.chuangdian.oflauncher.widgets.system;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.widget.Toast;
import cn.onekit.CONFIG;
import cn.onekit.JSON;

public abstract class HttpUtils {
	String name;
	// LocationClient mLocationClient;
	Activity context;

	public HttpUtils(String name/* , LocationClient mLocationClient */, Activity context) {
		this.name = name;
		// this.mLocationClient = mLocationClient;
		this.context = context;
	}

	/**
	 * 获取数据
	 */
	public void loadWeather() {

		if (isInterent.hasInternet(context)) {// 判断是否有网络
			GetFirstWeather(); // 网上获取并解析然后保存
		} else {// 读取缓存然后解析
			Toast.makeText(context, "无法连接到网络", Toast.LENGTH_SHORT).show();
			loadLocal();
		}
	}

	/**
	 * 网络请求数据
	 */
	public void GetFirstWeather() {
		new Thread() {
			@Override
			public void run() {
				URL url;
				String cityname = null;
				// mLocationClient.requestLocation();
				if (name.contains("市") || name.contains("省")) {
					cityname = name.substring(0, name.length() - 1);
				}

				String path = "https://api.heweather.com/x3/weather?city=" + "成都"
						+ "&key=2f1fc03c1fc84b399113984e8256c6af";
				// String path =
				// "http://apistore.baidu.com/microservice/weather?cityname=" +
				// cityname;
				try {
					url = new URL(toBrowserCode(path));
					HttpURLConnection con = (HttpURLConnection) url.openConnection();
					con.setRequestMethod("GET");
					con.setConnectTimeout(8000);
					con.setReadTimeout(8000);

					InputStream responseStream = con.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));

					StringBuffer result = new StringBuffer();

					String line = "";
					while ((line = reader.readLine()) != null) {
						result.append(line);
					}
					saveLocal(result.toString());

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}.start();
	}

	/**
	 * 解析json
	 * 
	 * @param json
	 */
	public abstract void paseJson(String json);

	/**
	 * 保存到本地
	 * 
	 * @param json
	 */
	private void saveLocal(String json) {
		paseJson(json);
		JSONObject systemwidgets = JSON.parse(CONFIG.get("systemwidgets"));
		try {
			systemwidgets.put("weather", json);
			CONFIG.set("systemwidgets", systemwidgets);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载本地数据
	 * 
	 */
	private void loadLocal() {
		String weatherInfo = null;
		Object temp = CONFIG.get(context, "systemwidgets");
		if (temp != null) {
			JSONObject systemwidgets = JSON.parse(temp);
			try {
				weatherInfo = systemwidgets.getString("weather");
				paseJson(weatherInfo);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			CONFIG.set(context, "systemwidgets", new JSONArray());
		}

	}

	private static final String HEX_STRING = "0123456789ABCDEF";

	public String toBrowserCode(String word) {
		byte[] bytes = word.getBytes();

		// 不包含中文，不做处理
		if (bytes.length == word.length())
			return word;

		StringBuilder browserUrl = new StringBuilder();
		String tempStr = "";

		for (int i = 0; i < word.length(); i++) {
			char currentChar = word.charAt(i);

			// 不需要处理
			if ((int) currentChar <= 256) {

				if (tempStr.length() > 0) {
					byte[] cBytes = tempStr.getBytes();

					for (int j = 0; j < cBytes.length; j++) {
						browserUrl.append('%');
						browserUrl.append(HEX_STRING.charAt((cBytes[j] & 0xf0) >> 4));
						browserUrl.append(HEX_STRING.charAt((cBytes[j] & 0x0f) >> 0));
					}
					tempStr = "";
				}

				browserUrl.append(currentChar);
			} else {
				// 把要处理的字符，添加到队列中
				tempStr += currentChar;
			}
		}
		return browserUrl.toString();
	}

}
